from flask import Blueprint, request
from app.services.UserService import UserService
from app.response import ResponseBuilder
from flask_login import login_required, current_user
import json
prefix = '/sys_user' 

main_bp = Blueprint('main', __name__, url_prefix=prefix)

@main_bp.route('/create_user', methods=['POST'])
def get_user():
    user_service = UserService()
    name = request.json.get('name')
    email = request.json.get('email')
    phone = request.json.get('phone')
    password = request.json.get('password')
    role = request.json.get('role')
    status = request.json.get('status')
    avatar = request.json.get('avatar')

    user_service.create_user_service(name=name, email=email, phone=phone, password=password, role=role, status=status, avatar=avatar)
    return ResponseBuilder.success('success')


@main_bp.route('/update_user', methods=['PUT'])
def update_user():
    user_service = UserService()
    id = request.json.get('id')
    name = request.json.get('name')
    email = request.json.get('email')
    phone = request.json.get('phone')
    role = request.json.get('role')
    status = request.json.get('status')
    avatar = request.json.get('avatar')
    user_service.update_user_service(id=id, name=name, email=email, phone=phone ,role=role, status=status, avatar=avatar)
    return ResponseBuilder.success('success')

@main_bp.route('/remove_user', methods=['DELETE'])
def delete_user():
    user_service = UserService()
    ids = request.json.get('ids')
    user_service.delete_user_service(ids=ids)
    return ResponseBuilder.success('success')

@main_bp.route('/get_user_by_id', methods=['GET'])
def get_user_by_id():
    user_service = UserService()
    user_id = request.args.get('user_id')
    user = user_service.get_user_service(user_id=user_id)
    return ResponseBuilder.success(user.to_dict())

@main_bp.route('/get_users', methods=['GET'])
def get_user_by_name():
    user_service = UserService()
    page_num = int(request.args.get('pageNum'))
    page_size = int(request.args.get('pageSize'))
    name = request.args.get('name')
    email = request.args.get('email')
    phone = request.args.get('phone')
    role = request.args.get('role')
    status = request.args.get('status')
    users = user_service.get_user_list_service(page_num=page_num, page_size=page_size, name=name, email=email, phone=phone, role=role, status=status)
    total = user_service.get_user_total_service(name=name, email=email, phone=phone, role=role, status=status)
    users_list = [user.to_dict() for user in users]
    return ResponseBuilder.success({'list': users_list, 'total': total})

@main_bp.route('/get_myself', methods=['GET'])
@login_required
def get_myself():
    user_service = UserService()
    current_user
    user = user_service.get_user_service(user_id=current_user.id)
    return ResponseBuilder.success(user.to_dict())